﻿using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using AntDesign;
using Blazor.Core;
using Blazor.Core.Extensions;
using Blazor.Localization;
using Blazor.Model.Dto;
using Blazor.Pages.UpdateSetting.Modals.NewHotUpdateSetting;
using Blazor.ViewModels.UpdateSetting;
using Microsoft.Extensions.Localization;
using ReactiveUI;

namespace Blazor.Views.UpdateSetting;

public partial class Settings: SoraniComponentBase<SettingsViewModel>
{
    private readonly ModalService _modalService;
    private readonly IStringLocalizer<UpdateSettingLocalization> _loc;

    public Settings(ModalService modalService, IStringLocalizer<UpdateSettingLocalization> loc)
    {
        _modalService = modalService;
        _loc = loc;
    }

    protected override void BindWithViewModel(SettingsViewModel viewModel, CompositeDisposable disposable)
    {
        viewModel.DeleteNativeVersionInteraction.RegisterHandler(DeleteNativeVersionInteractionHandler).DisposeWith(disposable);
        viewModel.NewNativeVersionInteraction.RegisterHandler(NewNativeVersionInteractionHandler).DisposeWith(disposable);
    }

    private async Task NativeVersionClickHandler(MenuItem menuItem)
    {
        var key = menuItem.Key;

        if (key is null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (!uint.TryParse(key, out var nativeVersion))
        {
            throw new ArgumentException($"Invalid uint, {key}");
        }

        ViewModel!.ChangeNativeVersion.Execute(nativeVersion).Subscribe().DisposeWith(Disposables);
    }

    private async Task DeleteNativeVersionInteractionHandler(IInteractionContext<Unit, bool> interactionContext)
    {
        var confirm = await _modalService.ConfirmAsync(new ConfirmOptions()
        {
           Content = _loc[UpdateSettingLocalization.DeleteHotUpdateSettingTip].ToString()
        });

        interactionContext.SetOutput(confirm);
    }
    
    private async Task NewNativeVersionInteractionHandler(IInteractionContext<Unit, KeyValuePair<uint, HotUpdateInfo>?> interactionContext)
    {
        var result = await _modalService.OpenCustomModal<NewHotUpdateSettingModal, Empty, NewHotUpdateSettingResult?>(new Empty());

        if (result is not null)
        {
            var value = result.Value;
            interactionContext.SetOutput(new KeyValuePair<uint, HotUpdateInfo>(value.NativeVersion, new HotUpdateInfo
            {
                ResourceUrl = value.ResourceUrl.ToString(),
                ResourceVersion = value.ResourceVersionEntry,
                Whitelist = new Dictionary<string, ResourceVersionEntry>(),
            }));
        }
        else
        {
            interactionContext.SetOutput(null);
        }
    }
}